﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using System.Web.Routing;

namespace EM.OA.WebCommon
{
    /// <summary>
    /// 异常处理
    /// </summary>
    public class AppHandleErrorAttribute : HandleErrorAttribute
    {

        public override void OnException(ExceptionContext filterContext)
        {
            // 记日志
            Guid userID = Guid.NewGuid();
            string userIP = filterContext.HttpContext.Request.UserHostAddress;
            string desc = filterContext.Exception.Message;
            string url = filterContext.HttpContext.Request.RawUrl.ToString();
            SystemLog.WriteLog(null, userIP, null, desc, url, null);

            //GuardarError("EMOA", filterContext.Exception);

            //Exception ex = filterContext.Exception;
            //if (true)// (ex is WebException)
            //{
            //    //log.Error("自定义异常（WebException）：", ex);

            //    // 表示异常已处理，直接跳到500显示错误消息
            //    filterContext.ExceptionHandled = true;
            //    filterContext.Result = new RedirectToRouteResult("500", new RouteValueDictionary(new
            //    {
            //        message = ex.Message
            //    }));
            //}
            //else
            //{
            //    //log.Error("系统异常：", ex);
            //}
        }

        public static void GuardarError(string prmStrFuente, Exception prmObjException)
        {
            prmStrFuente = "EMOA";
            string mensaje = "Fuente: " + prmStrFuente + " \n "
                + "Exception Error: " + prmObjException.Message + " \n "
                + "Exception Source: " + prmObjException.Source + " \n "
                + "Exception Data: " + prmObjException.Data + " \n "
                + "Exception Trace: " + prmObjException.StackTrace;

            if (!EventLog.SourceExists(prmStrFuente))
            {
                EventLog.CreateEventSource(prmStrFuente, "EMOA Error");
            }
            EventLog.WriteEntry(prmStrFuente, mensaje, EventLogEntryType.Error);
        }
    }
}
